<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/19
 * Time: 14:19
 */

namespace app\index\controller;
use think\Db;
use app\index\model\Shop as ShopModel;
use think\Request;
use think\Url;

class Shop
{
    /**
     * @param $area_name
     * @param string $longitude
     * @param string $latitude
     * @return array
     * 门店列表
     */
    public function index($area_name, $longitude = '46.7731912817', $latitude = '126.6311421704')
    {

        write_log($longitude.'-'.$latitude);
        $area_id = Db::name('area')->where('area_name', 'like', '%' . $area_name . '%')->value('area_id');
        $list = (new ShopModel())
            ->where('auding_status', 2)
//            ->where('city_id', $area_id)
            ->where('is_delete', 1)
            ->where('status', 1)
            ->field('id,shop_title,thumbnail,shop_address,sale_number,longitude,latitude')->paginate(6)->each(function ($item, $key) use ($longitude, $latitude) {
                //$data = http_gets('https://restapi.amap.com/v3/direction/walking?origin=116.434307,39.90909&destination=116.434446,39.90816&key=fe1e97dc6d56d758cf297a8ee7ecf0f2');
                ///halt(json_decode($data,true)['route']['paths']['distance']);
                $data = http_gets('https://restapi.amap.com/v3/direction/walking?origin=116.434307,39.90909&destination='.$item['longitude'].','.$item['latitude'].'&key=fe1e97dc6d56d758cf297a8ee7ecf0f2');
                ///halt(json_decode($data,true)['route']['paths']['distance']);
                $url = 'https://restapi.amap.com/v3/direction/walking?origin='.$longitude.','.$latitude.'&destination='.$item['longitude'].','.$item['latitude'].'&key=fe1e97dc6d56d758cf297a8ee7ecf0f2';
                $data = $this->distance($latitude,$longitude,$item['latitude'],$item['longitude']);
                $item->distance = $data;
               //$item->distance = round(getDistance($item['longitude'], $item['latitude'], (float)$longitude, (float)$latitude), 1);
                $item->evaluate_count = Db::name('order_evaluate')->where('shop_id', $item->id)->where('auding_status',2)->count();
            });
        return ['code' => 200, 'message' => 'ok', 'data' => $list];
    }

    public function distance($lat1=22.5219047226735, $lng1=114.0540241785779, $lat2=23.13207021269571, $lng2=113.2713476642072){
        $url= 'https://restapi.amap.com/v3/distance?origins='.$lng1.','.$lat1.'&destination='.$lng2.','.$lat2.'&key=fe1e97dc6d56d758cf297a8ee7ecf0f2';

        writeLog(var_export($url,true));
        $result = json_decode(http_gets($url),true);
        return $result['results'][0]['distance']/1000;
        // 使用domdocument 来操作xml
        $xml = new \DOMDocument();
        // 解析xml类
        $xml->loadXML($result);
        // 处理xml数据  //xml 转为array
        $arr = getArray($xml->documentElement);
        //支持100个坐标对，取第一个
        return $arr['results'][0]['result']['distance'][0]['#text']/1000;

    }

    public function lujing(){
        //$url= 'https://restapi.amap.com/v3/distance?origins=126.622245,45.773316&destination=129.720782,44.574066&key=fe1e97dc6d56d758cf297a8ee7ecf0f2';
        $url = 'https://restapi.amap.com/v3/direction/driving?origins=126.622245,45.773316&destination=129.720782,44.574066&key=fe1e97dc6d56d758cf297a8ee7ecf0f2';
        writeLog(var_export($url,true));
        $result = json_decode(http_gets($url),true);
    }

    /**
     * @param $id
     * @param string $longitude
     * @param string $latitude
     * @return array
     * 门店详情
     */
    public function view($id, $longitude = '46.7731912817', $latitude = '126.6311421704',$member_id = 0)
    {
        writeLog(var_export($longitude.'-'.$latitude,true));
        $info = (new ShopModel())->where('id', $id)->field('id,shop_title,shop_address,shop_phone,picArr,longitude,latitude')->find();
        $info['picArr'] = unserialize($info['picArr']) ? unserialize($info['picArr']) : [];
        $info['distance'] = round(getDistance($info['longitude'], $info['latitude'], (float)$longitude, (float)$latitude), 1);

        if(!empty($member_id)){
            $auding_status['shop_id'] = ['eq', $id];
            $auding_status['oe.member_id'] = ['eq', $member_id];
            $others_evaluate = function ($query) use ($id) {
                $query->where('auding_status', 'eq', '2')->where('shop_id', 'eq', $id);
            };
            $info['evaluate_count'] = Db::name('order_evaluate oe')->where($auding_status)->whereOr($others_evaluate)->count();
            $info['list'] = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id')
                ->field('oe.*,m.username,m.nickname,m.avatar head_pic')
                ->where($auding_status)->whereOr($others_evaluate)
                ->order('oe.id','desc')
                ->paginate(8);
        }else{
            $info['evaluate_count'] = Db::name('order_evaluate oe')->where('shop_id', $info->id)->where('auding_status',2)->count();
            $info['list'] = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id')
                ->field('oe.*,m.username,m.nickname,m.avatar head_pic')
                ->where('auding_status',2)
                ->order('oe.id','desc')
                ->where('shop_id', $info->id)->paginate(3);
        }
        $info['content'] = Request::instance()->domain() . Url::build('html', ['id' => $info['id']]);
        return ['code' => 200, 'message' => 'ok', 'data' => $info];
    }

    public function jl(){
        $data = http_gets('https://restapi.amap.com/v3/direction/walking?origin=116.434307,39.90909&destination=116.434446,39.90816&key=fe1e97dc6d56d758cf297a8ee7ecf0f2');
        halt(json_decode($data,true)['route']['paths']['distance']);
    }

    public function html($id)
    {
        $content = '<style> img {vertical-align:middle; width:auto; max-width:95%;} </style>';
        $content .= '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">';
        $content .= Db::name('shop')->where('id', $id)->value('content');
        return response($content);
    }

    /**
     * 门店所有评价列表
     * @param $id
     * @return array
     */
    public function evaluate_index($id,$member_id)
    {
        $list = Db::name('order_evaluate oe')
            ->join('member m', 'oe.member_id = m.id')
            ->where('auding_status',2)
            ->field('oe.*,DATE_FORMAT(oe.create_time,"%Y-%m-%d") create_time,oe.pic_url,m.username,m.nickname,m.avatar head_pic')
            ->where('shop_id', $id)->paginate(6);
        if(!empty($member_id)){
            $auding_status['shop_id'] = ['eq', $id];
            $auding_status['member_id'] = ['eq', $member_id];
            $others_evaluate = function ($query) use ($id) {
                $query->where('auding_status', 'eq', '2')->where('shop_id', 'eq', $id);
            };
            $list = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id')
                ->order('oe.id','desc')
                ->where($auding_status)->whereOr($others_evaluate)
                ->field('oe.*,DATE_FORMAT(oe.create_time,"%Y-%m-%d") create_time,oe.pic_url,m.username,m.nickname,m.avatar head_pic')
                ->where('shop_id', $id)->paginate(6);
        }else{
            $list = Db::name('order_evaluate oe')
                ->join('member m', 'oe.member_id = m.id')
                ->where('auding_status',2)
                ->order('oe.id','desc')
                ->field('oe.*,DATE_FORMAT(oe.create_time,"%Y-%m-%d") create_time,oe.pic_url,m.username,m.nickname,m.avatar head_pic')
                ->where('shop_id', $id)->paginate(6);
        }
        return ['code' => 200, 'message' => '门店所有评价列表', 'data' => $list];
    }
}